// 初始化Mapbox
mapboxgl.accessToken = 'pk.eyJ1IjoibnB5ZmhwaGsiLCJhIjoiY21ienl3cmo5MjM5eTJucG1wMjBya2xxYSJ9.1lmG05cOcFpfIsUwDDNiFw';
const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [116.404, 39.915], // 北京中心坐标
    zoom: 12
});

// 示例GeoJSON数据 - 模拟河流数据
const riverData = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "name": "河流1",
                "color": "#1E90FF",
                "级别": 1
            },
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [116.39, 39.91],
                    [116.40, 39.915],
                    [116.41, 39.92]
                ]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "name": "河流2",
                "color": "#4169E1",
                "级别": 2
            },
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [116.395, 39.905],
                    [116.405, 39.91],
                    [116.415, 39.925]
                ]
            }
        }
    ]
};

// 为每个要素添加ID
riverData.features.forEach((feature, index) => {
    feature.id = index;
});

let heighLight = null;

map.on('load', () => {
    // 添加河流数据源
    map.addSource('riverDanger', {
        type: 'geojson',
        data: riverData
    });

    // 添加河流图层
    map.addLayer({
        id: 'riverDanger',
        type: 'line',
        source: 'riverDanger',
        paint: {
            'line-opacity': 1,
            'line-color': [
                'case',
                ['boolean', ['feature-state', 'select'], false],
                'rgb(0,255,255)', // 高亮颜色
                ['get', 'color']   // 默认颜色
            ],
            'line-width': [
                'case',
                ['boolean', ['feature-state', 'select'], false],
                4, // 高亮宽度
                2  // 默认宽度
            ]
        }
    });

    // 鼠标悬停事件
    map.on('mousemove', 'riverDanger', (e) => {
        if (e.features.length > 0) {
            if (heighLight !== null) {
                map.setFeatureState(
                    { source: 'riverDanger', id: heighLight },
                    { select: false }
                );
            }
            heighLight = e.features[0].id;
            map.setFeatureState(
                { source: 'riverDanger', id: heighLight },
                { select: true }
            );
        }
    });

    // 鼠标离开事件
    map.on('mouseleave', 'riverDanger', () => {
        if (heighLight !== null) {
            map.setFeatureState(
                { source: 'riverDanger', id: heighLight },
                { select: false }
            );
        }
        heighLight = null;
    });
});